package com.lsyonlygoddes.util;

import com.lsyonlygoddes.vo.FileVo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileUtils {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 返回一个file对象
     * @param parentPath
     * @return
     */
    public static List<FileVo> fileList(String parentPath) {

        List<FileVo> res = new ArrayList<>();

        File parentFolder = new File(parentPath);
        if (!parentFolder.isDirectory()) {
            return Collections.emptyList();
        }
        File[] files = parentFolder.listFiles();
        if (files == null || files.length == 0) {
            return Collections.emptyList();
        }
        for (File file : files) {
            if (file.isDirectory()) continue;
            FileVo fileVo = new FileVo();
            fileVo.setFileName(file.getName());
            fileVo.setModifyDate(getModifyDate(file));
            fileVo.setType(getFileType(file));

            res.add(fileVo);
        }

        return res;
    }

    private static String getFileType(File file) {
        if (file == null) return "";
        String fileName = file.getName();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        return fileType;
    }

    private static String getModifyDate(File file) {
        if (file == null) return "";
        String modifyDate = dateFormat.format(file.lastModified());
        return modifyDate;
    }
}
